package com.agentai.system.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import com.agentai.framework.common.utils.PageResult;
import com.agentai.framework.mybatis.service.impl.BaseServiceImpl;
import com.agentai.system.convert.SysSerialNoConvert;
import com.agentai.system.entity.SysSerialNoEntity;
import com.agentai.system.query.SysSerialNoQuery;
import com.agentai.system.vo.SysSerialNoVO;
import com.agentai.system.mapper.SysSerialNoMapper;
import com.agentai.system.service.SysSerialNoService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 系统序列号管理表
 *
 * @since 1.0.0 2024-11-09
 */
@Service
@AllArgsConstructor
public class SysSerialNoServiceImpl extends BaseServiceImpl<SysSerialNoMapper, SysSerialNoEntity> implements SysSerialNoService {

    private static Lock lock = new ReentrantLock(false);

    @Override
    public PageResult<SysSerialNoVO> page(SysSerialNoQuery query) {
        IPage<SysSerialNoEntity> page = baseMapper.selectPage(getPage(query), getWrapper(query));

        return new PageResult<>(SysSerialNoConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    private LambdaQueryWrapper<SysSerialNoEntity> getWrapper(SysSerialNoQuery query) {
        LambdaQueryWrapper<SysSerialNoEntity> wrapper = Wrappers.lambdaQuery();
        return wrapper;
    }

    @Override
    public void save(SysSerialNoVO vo) {
        SysSerialNoEntity entity = SysSerialNoConvert.INSTANCE.convert(vo);

        baseMapper.insert(entity);
    }

    @Override
    public void update(SysSerialNoVO vo) {
        SysSerialNoEntity entity = SysSerialNoConvert.INSTANCE.convert(vo);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, timeout = 30)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

    @Override
    public String getSeqNumberByType(String serialType) {

        String seqNumber = null;
        try {
            lock.lock();
            seqNumber = baseMapper.getSeqNumberByType(serialType, 1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return seqNumber;
    }

}
